import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { printerApi, PrintTask, PrintTaskParams } from '../../services/printerApi';
import './printer-detail.css';

interface FileItem {
  id: string;
  name: string;
  originalName: string;
  size: number;
  type: string;
  createdAt: Date;
}

const PrinterDetail: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [printer, setPrinter] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'files' | 'tasks'>('files');
  const [isDragging, setIsDragging] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [tasks, setTasks] = useState<PrintTask[]>([]);
  const [files, setFiles] = useState<FileItem[]>([]);
  const [selectedTask, setSelectedTask] = useState<PrintTask | null>(null);
  const [showPrintDialog, setShowPrintDialog] = useState(false);
  const [printCopies, setPrintCopies] = useState(1);
  const [isColorPrint, setIsColorPrint] = useState(false);
  const [printQuality, setPrintQuality] = useState<'draft' | 'normal' | 'high'>('normal');
  const [printFormat, setPrintFormat] = useState<'image/urf' | 'image/pwg-raster' | 'application/octet-stream'>('image/urf');
  const [colorMode, setColorMode] = useState<'auto' | 'color' | 'auto-monochrome' | 'monochrome'>('monochrome');
  const [selectedFile, setSelectedFile] = useState<FileItem | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 加载打印机信息和任务列表
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        setError(null);
        const printerData = await printerApi.getPrinter(id!);
        setPrinter(printerData);
        
        // 加载文件列表
        const filesData = await printerApi.getPrinterFiles(id!);
        setFiles(filesData);
        
        // 加载任务列表
        const tasksData = await printerApi.getPrinterTasks(id!);
        setTasks(tasksData);
      } catch (err) {
        console.error('加载数据失败:', err);
        setError('加载数据失败，请重试');
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [id]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      handleUploadFile(file);
    }
  }, []);

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      const file = files[0];
      handleUploadFile(file);
    }
  }, []);

  const handleUploadFile = async (file: File) => {
    try {
      setUploadProgress(0);
      // 开始上传进度动画
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) return 90; // 保持在90%直到上传完成
          return prev + 10;
        });
      }, 200);

      // 上传文件
      const uploadedFile = await printerApi.uploadFile(file, Number(id));
      
      // 上传完成，设置进度为100%
      setUploadProgress(100);
      setTimeout(() => setUploadProgress(0), 1000);
      clearInterval(progressInterval);

      // 更新文件列表
      setFiles(prev => [uploadedFile, ...prev]);
    } catch (error) {
      console.error('上传文件失败:', error);
      setError('上传文件失败，请重试');
    }
  };

  const handleDeleteFile = async (fileId: string) => {
    try {
      await printerApi.deleteFile(fileId);
      setFiles(prev => prev.filter(file => file.id !== fileId));
      setTasks(prev => prev.filter(task => task.fileId !== fileId));
    } catch (error) {
      console.error('删除文件失败:', error);
      setError('删除文件失败，请重试');
    }
  };

  const handleCreateTask = async (fileId: string, fileName: string) => {
    try {
      setSelectedFile(files.find(file => file.id === fileId) || null);
      
      // 默认选择 image/urf 格式 - 最常用、兼容性最好的格式
      setPrintFormat('image/urf');
      
      // 显示打印对话框
      setShowPrintDialog(true);
    } catch (error) {
      console.error('准备打印任务失败:', error);
      setError('准备打印任务失败，请重试');
    }
  };

  const handleDeleteTask = async (taskId: string) => {
    try {
      await printerApi.deleteTask(id!, taskId);
      setTasks(prev => prev.filter(task => task.id !== taskId));
    } catch (error) {
      console.error('删除任务失败:', error);
      setError('删除任务失败，请重试');
    }
  };

  const handlePrintConfirm = async () => {
    if (!selectedFile) return;

    try {
      setLoading(true);
      // 1. Create task with print parameters
      const printParams: PrintTaskParams = {
        copies: printCopies,
        color: isColorPrint,
        colorMode: colorMode,
        quality: printQuality,
        format: printFormat
      };
      
      console.log('创建打印任务，参数:', printParams);
      const newTask = await printerApi.createTask(Number(id), selectedFile.id, printParams);
      
      // 2. Update task list
      setTasks(prev => [newTask, ...prev]);
      
      // 3. Execute print action
      console.log('执行打印任务:', newTask.id);
      const printResult = await printerApi.printTask(id!, newTask.id);
      
      // 4. 根据打印结果处理
      if (printResult.success) {
        // 成功打印
        console.log('打印成功:', printResult);
        
        // 更新任务状态
        setTasks(prev => prev.map(task =>
          task.id === newTask.id
            ? { ...task, status: 'printing' }
            : task
        ));
        
        // 显示成功消息
        setSuccess('打印任务已发送到打印机');
      } else {
        // 打印失败
        console.error('打印失败:', printResult.error);
        setError(printResult.error || '打印失败，请重试');
        
        // 更新任务状态为失败
        setTasks(prev => prev.map(task =>
          task.id === newTask.id
            ? { ...task, status: 'failed', errorMessage: printResult.error }
            : task
        ));
      }
      
      // 5. Reset dialog
      setShowPrintDialog(false);
      setSelectedFile(null);
      
      // 刷新任务列表
      const tasksData = await printerApi.getPrinterTasks(id!);
      setTasks(tasksData);
    } catch (error: any) {
      console.error('打印过程发生错误:', error);
      setError(error.message || '打印失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const formatFileSize = (size: number) => {
    if (size < 1024) return `${size} B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
    return `${(size / (1024 * 1024)).toFixed(1)} MB`;
  };

  const renderPrintDialog = () => {
    if (!showPrintDialog) return null;
    
    return (
      <div className="print-dialog-overlay">
        <div className="print-dialog">
          <h2>打印设置</h2>
          <div className="print-dialog-content">
            {selectedFile && (
              <div className="print-file-info">
                <span className="file-name">{selectedFile.originalName}</span>
                <span className="file-size">({formatFileSize(selectedFile.size)})</span>
              </div>
            )}
            
            <div className="print-option">
              <label>打印份数</label>
              <input 
                type="number" 
                min="1" 
                max="100"
                value={printCopies} 
                onChange={(e) => setPrintCopies(parseInt(e.target.value) || 1)}
              />
            </div>
            
            <div className="print-option">
              <label>颜色模式</label>
              <select 
                value={colorMode} 
                onChange={(e) => setColorMode(e.target.value as 'auto' | 'color' | 'auto-monochrome' | 'monochrome')}
              >
                <option value="auto">自动</option>
                <option value="color">彩色</option>
                <option value="auto-monochrome">自动黑白</option>
                <option value="monochrome">黑白</option>
              </select>
            </div>
            
            <div className="print-option">
              <label>打印质量</label>
              <select 
                value={printQuality} 
                onChange={(e) => setPrintQuality(e.target.value as 'draft' | 'normal' | 'high')}
              >
                <option value="draft">草稿</option>
                <option value="normal">正常</option>
                <option value="high">高质量</option>
              </select>
            </div>
            
            <div className="print-option">
              <label>打印格式</label>
              <div className="format-options">
                <div 
                  className={`format-option ${printFormat === 'image/urf' ? 'selected' : ''}`}
                  onClick={() => setPrintFormat('image/urf')}
                >
                  <div className="format-name">URF</div>
                  <div className="format-desc">Apple 通用栅格格式</div>
                  <div className="format-recommended">推荐</div>
                </div>
                <div 
                  className={`format-option ${printFormat === 'image/pwg-raster' ? 'selected' : ''}`}
                  onClick={() => setPrintFormat('image/pwg-raster')}
                >
                  <div className="format-name">PWG-Raster</div>
                  <div className="format-desc">PWG 标准栅格格式</div>
                </div>
                <div 
                  className={`format-option ${printFormat === 'application/octet-stream' ? 'selected' : ''}`}
                  onClick={() => setPrintFormat('application/octet-stream')}
                >
                  <div className="format-name">Raw</div>
                  <div className="format-desc">原始二进制数据</div>
                </div>
              </div>
              <div className="format-hint">
                选择"URF"格式通常可获得最佳兼容性和打印效果
              </div>
            </div>
          </div>
          
          <div className="print-dialog-actions">
            <button 
              className="cancel-button" 
              onClick={() => {
                setShowPrintDialog(false);
                setSelectedFile(null);
              }}
            >
              取消
            </button>
            <button 
              className="confirm-button"
              onClick={handlePrintConfirm}
            >
              打印
            </button>
          </div>
        </div>
      </div>
    );
  };

  // 文件列表渲染
  const renderFiles = () => {
    if (files.length === 0) {
      return (
        <div className="empty-list">
          <div className="empty-icon">📁</div>
          <p>没有文件，请上传文件</p>
        </div>
      );
    }

    return (
      <div className="file-list">
        {files.map(file => (
          <div className="file-item" key={file.id}>
            <div className="file-icon">
              {file.type.includes('pdf') ? '📄' : 
               file.type.includes('image') ? '🖼️' : 
               file.type.includes('word') ? '📝' : '📎'}
            </div>
            <div className="file-info">
              <div className="file-name">{file.originalName}</div>
              <div className="file-meta">
                <span>{formatFileSize(file.size)}</span>
                <span>{new Date(file.createdAt).toLocaleString()}</span>
              </div>
            </div>
            <div className="file-actions">
              <button 
                className="print-button"
                onClick={() => handleCreateTask(file.id, file.originalName)}
              >
                打印
              </button>
              <button 
                className="delete-button"
                onClick={() => handleDeleteFile(file.id)}
              >
                删除
              </button>
            </div>
          </div>
        ))}
      </div>
    );
  };

  // 错误提示
  const renderError = () => {
    if (!error) return null;
    return (
      <div className="error-message">
        <span>{error}</span>
        <button onClick={() => setError(null)}>×</button>
      </div>
    );
  };
  
  // 成功提示
  const renderSuccess = () => {
    if (!success) return null;
    return (
      <div className="success-message">
        <span>{success}</span>
        <button onClick={() => setSuccess(null)}>×</button>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <div className="loading-text">加载中...</div>
      </div>
    );
  }

  if (error || !printer) {
    return (
      <div className="error-container">
        <div className="error-icon">⚠️</div>
        <div className="error-text">{error || '打印机不存在'}</div>
        <button className="back-button" onClick={() => navigate('/printers')}>
          返回列表
        </button>
      </div>
    );
  }

  return (
    <div className="printer-detail-container">
      {uploadProgress > 0 && (
        <div className="upload-progress">
          <div className="progress-bar" style={{ width: `${uploadProgress}%` }} />
        </div>
      )}

      <div className="printer-detail-header">
        <div className="back-button" onClick={() => navigate('/printers')}>
          <span>← 返回</span>
        </div>
        <h1>{printer?.name || '打印机详情'}</h1>
      </div>
      
      {loading && <div className="loading-spinner">加载中...</div>}
      {renderError()}
      {renderSuccess()}

      <div className="detail-content">
        <div className="detail-section">
          <h2>打印机信息</h2>
          <div className="info-grid">
            <div className="info-item">
              <span className="info-label">名称</span>
              <span className="info-value">{printer.name}</span>
            </div>
            <div className="info-item">
              <span className="info-label">类型</span>
              <span className="info-value">
                {printer.isSystemPrinter ? '系统打印机' : '网络打印机'}
              </span>
            </div>
            {printer.ip && printer.ip !== 'localhost' && (
              <div className="info-item">
                <span className="info-label">连接方式</span>
                <span className="info-value">
                  {printer.ip.includes('USB') ? '💻 USB连接' : 
                   printer.ip.includes('串口') ? '🔌 串口连接' : 
                   `🌐 网络 (${printer.ip}${printer.port ? `:${printer.port}` : ''})`}
                </span>
              </div>
            )}
            {printer.protocol && (
              <div className="info-item">
                <span className="info-label">协议</span>
                <span className="info-value">{printer.protocol}</span>
              </div>
            )}
            <div className="info-item">
              <span className="info-label">状态</span>
              <span className={`info-value ${printer.isOnline ? 'text-success' : 'text-danger'}`}>
                {printer.isOnline ? '在线' : '离线'}
              </span>
            </div>
            {printer.lastOnline && (
              <div className="info-item">
                <span className="info-label">最后在线时间</span>
                <span className="info-value">
                  {new Date(printer.lastOnline).toLocaleString()}
                </span>
              </div>
            )}
            {printer.description && (
              <div className="info-item">
                <span className="info-label">描述</span>
                <span className="info-value">{printer.description}</span>
              </div>
            )}
          </div>
        </div>

        <div className="detail-section">
          <h2>打印统计</h2>
          <div className="stats-grid">
            <div className="stat-card">
              <div className="stat-value">{printer.taskCount || 0}</div>
              <div className="stat-label">总任务数</div>
            </div>
            <div className="stat-card">
              <div className="stat-value">{printer.todayPrintCount || 0}</div>
              <div className="stat-label">今日打印</div>
            </div>
            <div className="stat-card">
              <div className="stat-value">{printer.failedPrintCount || 0}</div>
              <div className="stat-label">失败任务</div>
            </div>
          </div>
        </div>

        <div className="detail-section">
          <div
            className={`upload-area ${isDragging ? 'dragging' : ''}`}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
          >
            <input
              type="file"
              ref={fileInputRef}
              style={{ display: 'none' }}
              onChange={handleFileSelect}
              accept=".pdf,.docx"
            />
            <div className="upload-icon">📁</div>
            <div className="upload-text">点击或拖拽文件到此处上传</div>
            <div className="upload-hint">支持 PDF、Word 文档</div>
          </div>

          <div className="task-tabs">
            <button
              className={`task-tab ${activeTab === 'files' ? 'active' : ''}`}
              onClick={() => setActiveTab('files')}
            >
              文件列表
            </button>
            <button
              className={`task-tab ${activeTab === 'tasks' ? 'active' : ''}`}
              onClick={() => setActiveTab('tasks')}
            >
              打印任务
            </button>
          </div>

          {activeTab === 'files' && (
            renderFiles()
          )}

          {activeTab === 'tasks' && (
            <div className="task-list">
              {tasks.map(task => (
                <div key={task.id} className="task-item">
                  <div className="task-info">
                    <div className="task-name">{task.originalName}</div>
                    <div className="task-meta">
                      <span>{new Date(task.createdAt).toLocaleString()}</span>
                      <span className="task-copies">{task.copies} 份</span>
                      <span className={`task-status status-${task.status}`}>
                        {task.status === 'pending' && '等待打印'}
                        {task.status === 'printing' && '打印中'}
                        {task.status === 'completed' && '已完成'}
                        {task.status === 'failed' && '打印失败'}
                      </span>
                    </div>
                  </div>
                  <div className="task-actions">
                    {task.status === 'pending' && (
                      <button
                        className="print-button"
                        onClick={() => handleCreateTask(task.id, task.originalName)}
                      >
                        打印
                      </button>
                    )}
                    <button
                      className="delete-button"
                      onClick={() => handleDeleteTask(task.id)}
                    >
                      删除
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {renderPrintDialog()}
    </div>
  );
};

export default PrinterDetail;
